#include <unistd.h>
#include <stdio.h>
#include "mosquitto.h"

static void mqtt_message_callback(struct mosquitto *mosq, void *userdata,
               const struct mosquitto_message *message);
static void mqtt_connect_callback(struct mosquitto *mosq, void *userdata, int code);
static void mqtt_disconnect_callback(struct mosquitto *mosq, void *userdata, int code);

int main(int argc, char **argv)
{
  char topic[1024] = {0};
  const char *ip = "0.0.0.0", *user = "admin", *pw = "123456";
  void *mqtt = NULL;
  int rc = 0, port = 1883;
//mqtt
	mosquitto_lib_init();
  mqtt = mosquitto_new("robot", true, NULL);
  if (mqtt == NULL) {
    printf("mosquitto new is error\n");
    goto out;
  }
  mosquitto_message_callback_set(mqtt, mqtt_message_callback);
  mosquitto_connect_callback_set(mqtt, mqtt_connect_callback);
  mosquitto_disconnect_callback_set(mqtt, mqtt_disconnect_callback);
  mosquitto_user_data_set(mqtt, NULL);
  mosquitto_username_pw_set(mqtt, user, pw);
	do {
		rc = mosquitto_connect(mqtt, ip, port, 60);
		if (rc != MOSQ_ERR_SUCCESS) {
			printf("waiting connect err:%d\t%s[%d]\n", rc, ip, port);
			sleep(30);
		}
	} while (rc != MOSQ_ERR_SUCCESS);
	printf("mosquitto connect:%s[%d]\n", ip, port);
	do {
		rc = mosquitto_loop_start(mqtt);
		if (rc != MOSQ_ERR_SUCCESS) {
			printf("waiting mosquitto loop sqlite error\n");
			sleep(3);
		}
	} while (rc != MOSQ_ERR_SUCCESS);
  snprintf(topic, sizeof(topic), "EC_GW/S2C/C8/+");
  rc = mosquitto_subscribe(mqtt, NULL, topic, 1);
  if (rc != MOSQ_ERR_SUCCESS) {
    mosquitto_disconnect(mqtt);
    goto out;
  }
  printf("subscribe topic: %s \n", topic);
  while (1)
  {
    sleep (1);
  }
out:
	return rc;
}
static void mqtt_disconnect_callback(struct mosquitto *mosq, void *userdata, int code)
{
  mosquitto_reconnect(mosq);
  printf("reconnect\n");
}
static void mqtt_connect_callback(struct mosquitto *mosq, void *userdata, int code)
{
  mosquitto_subscribe(mosq, NULL, "test", 1);
  printf("subscribe:test\n");
}
static void mqtt_message_callback(struct mosquitto *mosq, void *userdata,
               const struct mosquitto_message *message)
{
  printf("[%s]:%d\n", message->topic, message->payloadlen);
}
